package cn.fl.capital.controller;

import cmm.mid.core.framework.page.DataResultVO;
import cmm.mid.core.framework.page.KeyValueVO;
import cmm.mid.core.framework.page.ListPageVO;
import cmm.mid.core.framework.page.Pager;
import cmm.web.core.framework.controller.BaseController;
import cn.cmm.base.framework.constant.BaseConstant;
import cn.cmm.base.framework.exception.BaseException;
import cn.cmm.base.framework.utils.BaseLogUtils;
import cn.cmm.base.framework.utils.CollectionUtils;
import cn.cmm.base.framework.utils.DateUtils;
import cn.cmm.base.framework.utils.DecimalUtils;
import cn.cmm.base.framework.utils.StringUtils;
import cn.fl.capital.condition.CapFeeOutLogQueryCondition;
import cn.fl.capital.constant.CapitalConstant;
import cn.fl.capital.dto.CapFeeOutLogDTO;
import cn.fl.capital.service.ICapFeeOutLogService;
import cn.fl.capital.vo.CapFeeOutLogVO;
import cn.fl.framework.base.context.CurrentThreadContext;
import cn.fl.project.service.IPrjPrdPaySchMService;
import cn.fl.project.vo.PrjPrdPaySchDVO;
import cn.fl.project.vo.PrjPrdPaySchMVO;
import cn.fl.system.constant.SysLogConstant;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import net.sf.json.JSONArray;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @Description: 支付表费用转出记录表 控制层
 */
@Controller
@RequestMapping("/capital/capFeeOutLog")
public class CapFeeOutLogController extends BaseController {
    private static final Logger logger = LoggerFactory.getLogger(CapFeeOutLogController.class);

    /**
     * CapFeeOutLog 服务层BEAN
     */
    @Autowired
    private ICapFeeOutLogService capFeeOutLogService;

    @Autowired
    private IPrjPrdPaySchMService prjPrdPaySchMService;

    /**
     * 到保证金转出管理页面
     */
    @RequestMapping(value = "/toFeeOutPage.do", method = {RequestMethod.GET})
    public ModelAndView toFeeOutPage(HttpServletRequest request, HttpServletResponse response) {
        BaseLogUtils.info(logger, "toListPage", "加载到保证金转出管理页面.", CurrentThreadContext.getCurrentUserName());
        ModelAndView mav = new ModelAndView("capital/capFeeOutLog/capFeeOutLog");
        return mav;
    }

    /**
     * 到列表页面
     */
    @RequestMapping(value = "/toListPage.do", method = {RequestMethod.GET})
    public ModelAndView toListPage(HttpServletRequest request, HttpServletResponse response) {
        BaseLogUtils.info(logger, "toListPage", "加载CapFeeOutLog列表页面.", CurrentThreadContext.getCurrentUserName());
        ModelAndView mav = new ModelAndView("capital/capFeeOutLog/capFeeOutList");
        String qtype = request.getParameter("qtype");//查询类型：0：保证金转出 1：保证金转出记录
        if (String.valueOf(BaseConstant.IS_YESNO_YES).equals(qtype)) {
            mav.setViewName("capital/capFeeOutLog/capFeeOutLogList");
            this.prepare(request, mav);
        }
        return mav;
    }

    /**
     * 到新增页面
     */
    @RequestMapping(value = "/toAddPage.do", method = {RequestMethod.GET, RequestMethod.POST})
    public ModelAndView toAddPage(HttpServletRequest request, HttpServletResponse response) {
        BaseLogUtils.info(logger, "toAddPage", "加载CapFeeOutLog Add页面.", CurrentThreadContext.getCurrentUserName());
        ModelAndView mav = new ModelAndView("capital/capFeeOutLog/capFeeOutLogModify");
        this.prepare(request, mav);
        String paySchId = request.getParameter("paySchId");
        String paySchNo = request.getParameter("paySchNo");
        String paySchDId = request.getParameter("paySchDId");
        String outAmt = request.getParameter("outAmt");
        String feeTypCd = request.getParameter("feeTypCd");
        String relationId = request.getParameter("relationId");
        String feeAmt = request.getParameter("feeAmt");

        CapFeeOutLogVO vo = new CapFeeOutLogVO();
        vo.setPaySchNo(paySchNo);
        vo.setFeeTypCd(feeTypCd);
        if (StringUtils.isNotEmpty(paySchDId)) {
            vo.setPaySchDId(Long.parseLong(paySchDId));
        }
        if (StringUtils.isNotEmpty(paySchId)) {
            vo.setPaySchId(Long.parseLong(paySchId));
        }
        if (StringUtils.isNotEmpty(outAmt)) {
            vo.setOutAmt(Long.parseLong(outAmt));
        }
        if (StringUtils.isNotEmpty(relationId)) {
            vo.setBizDataId(Long.valueOf(relationId));
        }
        /*
        if (StringUtils.isNotEmpty(paySchId) && CapitalConstant.CODE_FEE_TYP_CD_02.equals(feeTypCd)) {
            PrjPrdPaySchMVO paySchMVO = this.prjPrdPaySchMService.selectById(Long.parseLong(paySchId));
            if (paySchMVO != null) {
                vo.setHandleWayCd(paySchMVO.getDpstHdlWayCd());
            }
        }*/

        //查询本次可以转出的金额，页面传入有可能不准确
        if (StringUtils.isNotBlank(feeAmt)) {
            CapFeeOutLogQueryCondition condition = new CapFeeOutLogQueryCondition();
            condition.setPaySchDId(vo.getPaySchDId());
            condition.setPaySchId(vo.getPaySchId());
            condition.setPaySchNo(vo.getPaySchNo());
            condition.setFeeTypCd(vo.getFeeTypCd());
            condition.setIsDel(BaseConstant.IS_YESNO_NO);
            List<CapFeeOutLogVO> feeOutLogVOList = this.capFeeOutLogService.searchList(condition);
            if (CollectionUtils.isNotEmpty(feeOutLogVOList)) {
                //待转出金额
                vo.setOutAmt(0L);
                //已转出的费用金额
                Long amt = Long.parseLong(feeAmt);
                for (CapFeeOutLogVO capFeeOutLogVO : feeOutLogVOList) {
                    amt -= capFeeOutLogVO.getOutAmt();
                }
                if (amt > 0) {
                    vo.setOutAmt(amt);
                }
            }
        }

        mav.addObject("capFeeOutLogVO", vo);
        return mav;
    }

    /**
     * 到修改页面
     */
    @RequestMapping(value = "/toModifyPage.do", method = {RequestMethod.GET, RequestMethod.POST})
    public ModelAndView toModifyPage(HttpServletRequest request, HttpServletResponse response) {
        BaseLogUtils.info(logger, "toModifyPage", "加载CapFeeOutLog Modify页面.", CurrentThreadContext.getCurrentUserName());
        ModelAndView mav = new ModelAndView("capital/capFeeOutLog/capFeeOutLogModify");
        this.prepare(request, mav);

        String id = request.getParameter("id");
        CapFeeOutLogVO capFeeOutLogVO = this.capFeeOutLogService.selectById(Long.valueOf(id));
        mav.addObject("capFeeOutLogVO", capFeeOutLogVO);
        return mav;
    }

    //加载数据字典数据、传值等 ？
    public void prepare(HttpServletRequest request, ModelAndView mav) {
        List<KeyValueVO> handleWayCdList = this.capFeeOutLogService.searchDictListByGrpCd(CapitalConstant.CODE_HANDLE_WAY_CD);
        List<KeyValueVO> feeTypCdList = this.capFeeOutLogService.searchDictListByGrpCd(CapitalConstant.CODE_FEE_TYP_CD);
        mav.addObject("handleWayCdList", JSON.toJSONString(handleWayCdList));
        mav.addObject("feeTypCdList", JSON.toJSONString(feeTypCdList));
    }

    /**
     * 初始化列表
     */
    @SuppressWarnings("unchecked")
    @RequestMapping(value = "/initList.do", method = {RequestMethod.GET})
    @ResponseBody
    public Object initCapFeeOutLogList(HttpServletRequest request, HttpServletResponse response) {
        String currentPage = request.getParameter("page");
        String pageSize = request.getParameter("pagesize");
        Pager page = new Pager();
        if (StringUtils.isNotEmpty(currentPage)) {
            page.setCurrentPage(Integer.parseInt(currentPage));
        }

        if (StringUtils.isNotEmpty(pageSize)) {
            page.setEveryPage(Integer.parseInt(pageSize));
        }

        CapFeeOutLogQueryCondition qc = new CapFeeOutLogQueryCondition();
        String paySchNo = request.getParameter("paySchNo");
        if (StringUtils.isNotBlank(paySchNo)) {
            qc.setPaySchNo(paySchNo.trim());
        }
        String feeTypCd = request.getParameter("feeTypCd");
        if (StringUtils.isNotBlank(feeTypCd)) {
            qc.setFeeTypCd(feeTypCd);
        }
        String handleWayCd = request.getParameter("handleWayCd");
        if (StringUtils.isNotBlank(handleWayCd)) {
            qc.setHandleWayCd(handleWayCd);
        }
        String qtype = request.getParameter("qtype");
        if (StringUtils.isNotBlank(qtype)) {
            qc.setQtype(qtype);
        }
        String paySchId = request.getParameter("paySchId");
        if (StringUtils.isNotEmpty(paySchId)) {
            qc.setPaySchId(Long.valueOf(paySchId));
        }
        String paySchIds = request.getParameter("paySchIds");
        if (StringUtils.isNotEmpty(paySchIds)) {
            List<Long> paySchIdList = JSON.parseArray(paySchIds, Long.class);
            qc.setPaySchIdList(paySchIdList);
        }
        page.setCondition(qc);

        BaseLogUtils.info(logger, "initCapFeeOutLogList", "初始化CapFeeOutLog列表页面数据.DATA:" + JSONObject.toJSONString(page), CurrentThreadContext.getCurrentUserName());
        Pager pager = this.capFeeOutLogService.searchListPage(page);
        List<CapFeeOutLogVO> list = (List<CapFeeOutLogVO>) pager.getResultList();
        ListPageVO<CapFeeOutLogVO> listPage = new ListPageVO<CapFeeOutLogVO>(list, pager.getTotalCount());
        return listPage;
    }

    /**
     * 资管结清，查询待转出的保证金列表
     * @param request
     * @return
     */
    @RequestMapping(value = "/initFeeOutLogListForZG.do", method = {RequestMethod.GET})
    @ResponseBody
    public Object initFeeOutLogListForZG(HttpServletRequest request) {
        CapFeeOutLogQueryCondition qc = new CapFeeOutLogQueryCondition();
        String paySchIds = request.getParameter("paySchIds");
        try {
            if (StringUtils.isNotEmpty(paySchIds)) {
                List<Long> paySchIdList = JSON.parseArray(paySchIds, Long.class);
                qc.setPaySchIdList(paySchIdList);
            }
            List<CapFeeOutLogDTO> capFeeOutLogDTOS = capFeeOutLogService.searchListForMore(qc);
            ListPageVO<CapFeeOutLogDTO> listPage = new ListPageVO<CapFeeOutLogDTO>(capFeeOutLogDTOS, capFeeOutLogDTOS.size());
            return listPage;
        } catch (BaseException e) {
            BaseLogUtils.error(logger, "initFeeOutLogListForZG", "初始化CapFeeOutLog列表页面数据.DATA:" + paySchIds, e);
            throw new BaseException("初始化CapFeeOutLog列表页面数据异常！cause：" + e.getMessage());
        } catch (Exception e) {
            BaseLogUtils.error(logger, "initFeeOutLogListForZG", "初始化CapFeeOutLog列表页面数据.DATA:" + paySchIds, e);
            throw new BaseException("初始化CapFeeOutLog列表页面数据异常！cause：" + e.getMessage());
        }
    }

    /**
     * 删除数据
     */
    @RequestMapping(value = "/removeByIds.do", method = {RequestMethod.POST})
    @ResponseBody
    public DataResultVO removeCapFeeOutLogByIds(HttpServletRequest request, HttpServletResponse response) throws BaseException {
        String ids = request.getParameter("ids");
        DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_DELETE_SUCC);
        if (StringUtils.isEmpty(ids)) {
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo(SysLogConstant.LOG_CMM_DATA_PK_IS_EMPTY);
            BaseLogUtils.info(logger, "removeCapFeeOutLogByIds", "删除CapFeeOutLog数据,主键参数为空!", CurrentThreadContext.getCurrentUserName());
            return result;
        }

        List<Long> idsList = new ArrayList<Long>();
        JSONArray idsArray = JSONArray.fromObject(ids);
        for (Object object : idsArray) {
            idsList.add(Long.valueOf(object.toString()));
        }

        try {
            boolean success = this.capFeeOutLogService.removeByIds(idsList);
            if (!success) {
                result.setSuccess(BaseConstant.IS_YESNO_NO);
                result.setInfo(SysLogConstant.LOG_CMM_DELETE_FAIL);
                BaseLogUtils.info(logger, "removeCapFeeOutLogByIds", "删除CapFeeOutLog数据失败,ID:" + idsList.toString(), CurrentThreadContext.getCurrentUserName());
            }
            BaseLogUtils.info(logger, "removeCapFeeOutLogByIds", "删除CapFeeOutLog数据成功,ID:" + idsList.toString(), CurrentThreadContext.getCurrentUserName());
        } catch (BaseException ex) {
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
            BaseLogUtils.info(logger, "removeCapFeeOutLogByIds", "删除CapFeeOutLog数据失败,ID:" + idsList.toString() + ".ERROR:" + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
        } catch (Exception ex) {
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
            BaseLogUtils.error(logger, "removeCapFeeOutLogByIds", "删除CapFeeOutLog数据失败,系统错误.ID:" + idsList.toString() + ".ERROR:" + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
        }
        return result;
    }

    /**
     * 得到一条记录
     *
     * @param request
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/getById.do", method = {RequestMethod.GET})
    @ResponseBody
    public Object getCapFeeOutLogById(HttpServletRequest request, HttpServletResponse response) throws BaseException {
        String id = request.getParameter("id");
        DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_OPERATE_SUCC);
        if (StringUtils.isEmpty(id)) {
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo(SysLogConstant.LOG_CMM_DATA_PK_IS_EMPTY);
            BaseLogUtils.info(logger, "getCapFeeOutLogById", "获取CapFeeOutLog数据,主键参数为空.", CurrentThreadContext.getCurrentUserName());
            return result;
        }

        try {
            CapFeeOutLogVO vo = this.capFeeOutLogService.selectById(Long.valueOf(id));
            if (null == vo) {
                result.setSuccess(BaseConstant.IS_YESNO_NO);
                result.setInfo(SysLogConstant.LOG_CMM_QUERY_DATA_IS_EMPTY);
                BaseLogUtils.info(logger, "getCapFeeOutLogById", "获取CapFeeOutLog数据不存在,ID:" + id, CurrentThreadContext.getCurrentUserName());
            }
            result.setData(vo);
            BaseLogUtils.info(logger, "getCapFeeOutLogById", "获取CapFeeOutLog数据成功,ID:" + id, CurrentThreadContext.getCurrentUserName());
        } catch (BaseException ex) {
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
            BaseLogUtils.info(logger, "getCapFeeOutLogById", "获取CapFeeOutLog数据失败,ID:" + id + ".ERROR:" + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
        } catch (Exception ex) {
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
            BaseLogUtils.error(logger, "getCapFeeOutLogById", "获取CapFeeOutLog数据失败,系统错误.ID:" + id + ".ERROR:" + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
        }
        return result;
    }

    /**
     * 新增
     */
    @RequestMapping(value = "/add.do", method = {RequestMethod.POST})
    @ResponseBody
    public Object addCapFeeOutLog(HttpServletRequest request, HttpServletResponse response) throws BaseException {
        DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_ADD_SUCC);
        CapFeeOutLogVO entity = null;//获取参数
        try {
            entity = this.getRequestParamForCapFeeOutLog(request);//获取参数
            Long id = this.capFeeOutLogService.add(entity);
            result.setData(id);
            BaseLogUtils.info(logger, "addCapFeeOutLog", "新增CapFeeOutLog数据成功,ID:" + id + ".DATA:" + JSONObject.toJSONString(entity), CurrentThreadContext.getCurrentUserName());
        } catch (BaseException ex) {
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR + ex.getMessage());
            BaseLogUtils.info(logger, "addCapFeeOutLog", "新增CapFeeOutLog数据失败.DATA:" + JSONObject.toJSONString(entity) + ".ERROR:" + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
        } catch (Exception ex) {
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR + ex.getMessage());
            BaseLogUtils.error(logger, "addCapFeeOutLog", "新增CapFeeOutLog数据失败,系统错误.DATA:" + JSONObject.toJSONString(entity) + ".ERROR:" + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
        }
        return result;
    }

    /**
     * 修改
     */
    @RequestMapping(value = "/modify.do", method = {RequestMethod.POST})
    @ResponseBody
    public Object modifyCapFeeOutLog(HttpServletRequest request, HttpServletResponse response) throws BaseException {
        DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_UPDATE_SUCC);
        CapFeeOutLogVO entity = null;
        try {
            entity = this.getRequestParamForCapFeeOutLog(request);
            if (entity.getId() == null) {
                result.setSuccess(BaseConstant.IS_YESNO_NO);
                result.setInfo(SysLogConstant.LOG_CMM_DATA_PK_IS_EMPTY);
                BaseLogUtils.info(logger, "modifyCapFeeOutLog", "修改CapFeeOutLog信息,主键参数为空！.", CurrentThreadContext.getCurrentUserName());
                return result;
            }

            boolean success = this.capFeeOutLogService.modify(entity);
            if (!success) {
                result.setSuccess(BaseConstant.IS_YESNO_NO);
                result.setInfo(SysLogConstant.LOG_CMM_UPDATE_FAIL);
                BaseLogUtils.info(logger, "modifyCapFeeOutLog", "修改CapFeeOutLog数据失败.DATA:" + JSONObject.toJSONString(entity), CurrentThreadContext.getCurrentUserName());
                return result;
            }
            BaseLogUtils.info(logger, "modifyCapFeeOutLog", "修改CapFeeOutLog数据成功.DATA:" + JSONObject.toJSONString(entity), CurrentThreadContext.getCurrentUserName());
        } catch (BaseException ex) {
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR + ex.getMessage());
            BaseLogUtils.info(logger, "modifyCapFeeOutLog", "修改CapFeeOutLog数据失败.DATA:" + JSONObject.toJSONString(entity) + ".ERROR:" + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
        } catch (Exception ex) {
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR + ex.getMessage());
            BaseLogUtils.error(logger, "modifyCapFeeOutLog", "修改CapFeeOutLog数据失败,系统错误.DATA:" + JSONObject.toJSONString(entity) + ".ERROR:" + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
        }
        return result;
    }

    /**
     * 获取请求参数
     *
     * @param request 请求
     * @return
     */
    private CapFeeOutLogVO getRequestParamForCapFeeOutLog(HttpServletRequest request) throws BaseException {
        //获取参数
        String id = request.getParameter("id");//主键
        String paySchId = request.getParameter("paySchId");//支付表ID
        String feeTypCd = request.getParameter("feeTypCd");//费用类型(CAP0018)  02.客户保证金 11.保险保证金 33.风险保证金 13.厂商保证金22.经销商保证金
        String handleWayCd = request.getParameter("handleWayCd");//保证金处理方式（CAP0017） 1.冲抵租金 2.冲抵返利 3.退还
        String outAmt = request.getParameter("outAmt");//转出金额（分）
        String outDt = request.getParameter("outDt");//转出时间
        String outRem = request.getParameter("outRem");//备注
        String paySchNo = request.getParameter("paySchNo");//支付表号
        String paySchDId = request.getParameter("paySchDId");//支付表明细ID（PRJ_PRD_PAY_SCH_D表主键）
        String bizDataId = request.getParameter("bizDataId");//业务数据主键

        //验证参数并赋值
        CapFeeOutLogVO entity = new CapFeeOutLogVO();
        if (StringUtils.isNotEmpty(paySchDId)) {
            entity.setPaySchDId(Long.parseLong(paySchDId));//支付表ID
        }
        if (StringUtils.isNotEmpty(paySchId)) {
            entity.setPaySchId(Long.parseLong(paySchId));
        }
        if (StringUtils.isNotEmpty(outAmt)) {
            outAmt.replace(",", "");
            entity.setOutAmt(DecimalUtils.convertYuanToFen(Double.parseDouble(outAmt)));
        }
        entity.setFeeTypCd(feeTypCd);//费用类型(CAP0018)  02.客户保证金 11.保险保证金 33.风险保证金 13.厂商保证金22.经销商保证金
        entity.setHandleWayCd(handleWayCd);//保证金处理方式（CAP0017） 1.冲抵租金 2.冲抵返利 3.退还
        if (StringUtils.isNotBlank(outDt)) {
            entity.setOutDt(DateUtils.formatStringToDate(outDt, DateUtils.YYYY_MM_DD));//转出时间
        }
        if (StringUtils.isNotBlank(bizDataId)) {
            entity.setBizDataId(Long.parseLong(bizDataId));
        }
        entity.setOutRem(outRem);//备注
        entity.setPaySchNo(paySchNo);//支付表号

        Date tm = new Date();
        if (StringUtils.isNotBlank(id)) {
            entity.setId(Long.valueOf(id));
            entity.setMdfTm(tm);
            entity.setMdfUsrId(CurrentThreadContext.getCurrentUserId());
        } else {
            entity.setCrtTm(tm);
            entity.setCrtUsrId(CurrentThreadContext.getCurrentUserId());
            entity.setCrtUsrNm(CurrentThreadContext.getCurrentUserName());
        }

        return entity;
    }
}

